<template>
  <div class="layout_2">
    <MyTable
      v-loading="loading"
      element-loading-text="疯狂加载中..."
      :data="userList"
      :label="label"
      :page-info="pageInfo"
      :add="false"
      :lef-span="13"
      @handle-size-change="handleSizeChange"
      @handle-current-change="handleCurrentChange"
      @handle-selection-change="handleSelectionChange"
      @delete-row="deleteRow"
      @search-user-info="searchUserInfo"
    >
      <template #add>
        <el-upload
          :show-file-list="false"
          action=""
          :before-upload="beforeUpload"
          :http-request="() => {}"
        >
          <el-button id="excle" type="primary" icon="Briefcase" text bg>导入excel</el-button>
        </el-upload>
        <el-upload
          :show-file-list="false"
          action=""
          :before-upload="beforeUpload2"
          :limit="10000"
          :http-request="() => {}"
          multiple
        >
          <el-button type="primary" class="avt" icon="PictureFilled" text bg>导入头像</el-button>
        </el-upload>
      </template>
      <template #right>
        <el-row>
          <el-col :span="21">
            <div id="search" style="display: flex">
              <!-- <el-input v-model="searchValue" placeholder="请输入姓名" maxlength="20"></el-input> -->
              <el-autocomplete
                v-model="searchValue"
                :fetch-suggestions="querySearchAsync"
                clearable
                class="inline-input"
                placeholder="请输入学号或姓名"
                @select="handleSelect"
              />
              <el-button type="primary" class="search" @click="search()">搜索</el-button>
            </div>
          </el-col>
          <el-col :span="3">
            <el-button :icon="Refresh" circle @click="reSet()" />
          </el-col>
        </el-row>
      </template>
    </MyTable>
    <el-dialog v-model="dialogTableVisible" width="800" title="学生基本信息表">
      <MyCard :user-info="userCard" @change-user-card="changeUserCard"></MyCard>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import MyTable from '../../components/my-table.vue'
import MyCard from '../../components/card.vue'
import { ElMessage } from 'element-plus'
import { initData } from '../../utils/initData'
import { useSqliteStore } from '../../store/sqliteData'
//测试提交
// import db from '../../../../../resources/db/sqlite3db'
// import JSZip from 'jszip' // 引入jszip
import * as XLSX from 'xlsx' // 引入xlsx
// import { useDataStore } from '../../store/data.js'
import { Refresh } from '@element-plus/icons-vue'
const dialogTableVisible = ref(false)
const loading = ref(false)
const sqliteData = useSqliteStore()
onMounted(async () => {
  init()
})
const list = ref([])
const userCard = ref(null)
// const dataStore = useDataStore()
const selectList = ref([]) // 选中的列表
const searchValue = ref('') // 搜索框内容
const label = ref([
  { label: '学号', prop: 'num' },
  { label: '姓名', prop: 'name' },
  { label: '性别', prop: 'sex' },
  { label: '头像', prop: 'pic' }
])
const searchUserInfo = (index) => {
  dialogTableVisible.value = true
  console.log(userList.value, index)
  changeUserCard(index)
}
//为card赋值
const changeUserCard = (index) => {
  //要么后端直接把所有数据返回，要么新建表查询
  console.log(userList.value.length)

  userCard.value = {
    ...userList.value[index],
    correct: 0,
    incorrect: 0,
    partiallyCorrect: 0,
    size: userList.value.length,
    index
  }
}
// const tempList = ref([]) // 临时列表
//下拉展示框
const querySearchAsync = async (queryString, cb) => {
  console.log(queryString)
  let res = await getUserData('pull', queryString)
  console.log(res)
  cb(
    res.data.list.map((e) => {
      return { value: e.name }
    })
  )
}
const handleSelect = (select) => {
  console.log(select)
}
const pageInfo = ref({
  page: 1,
  size: 10,
  total: 0
})
const copy = (obj) => {
  let jsonTemp = JSON.stringify(obj)
  let res = JSON.parse(jsonTemp)
  return res
}
//初始化配置
const init = async () => {
  let res = await getUserData('search')
  userList.value = res.data.list
  pageInfo.value.total = res.data.total
  console.log(res)
  // setupIpcListener()
}
//promise
const myPromise = (callback) => {
  return new Promise((resolve) => {
    callback((result) => {
      resolve(result)
    })
  })
}
const mainOut = window.electronAPI.mainOut
// const setupIpcListener = async () => {
//   return await myPromise((callback) => {})
// }
// const handleIpcResponse = async (data) => {
//   // 处理 IPC 响应
//   return new Promise((resolve, reject) => {})
// }

const userList = ref([])
const getUserData = async (type, value) => {
  var res
  if (type == 'pull') {
    await window.electronAPI.rendererSend('page', {
      page: 1,
      size: 10,
      name: value,
      num: value
    })
  }
  if (type == 'search') {
    let obj = {
      ...pageInfo.value,
      name: searchValue.value,
      num: searchValue.value
    }
    await window.electronAPI.rendererSend('page', copy(obj))
  }
  if (type == 'insert') {
    await window.electronAPI.rendererSend('insert', copy(value))
  }
  if (type == 'insertImage') {
    let list = chunkArray(value, 30)
    list.forEach(async (temp) => {
      await window.electronAPI.rendererSend('insertImage', copy(temp))
    })
  }
  if (type == 'delete') {
    await window.electronAPI.rendererSend('delete', copy(value))
  }
  res = await myPromise((callback) => {
    mainOut(callback)
  })
  // await mainOut((res1) => {
  //   res = res1
  //   console.log(res1)
  // })
  console.log('thisRes', res)
  return res?.data
}
// 分割数组
function chunkArray(array, size) {
  const result = []
  for (let i = 0; i < array.length; i += size) {
    const chunk = array.slice(i, i + size)
    result.push(chunk)
  }
  return result
}
//渲染data数据
const setUserList = async () => {
  let res = await getUserData('search')
  userList.value = res.data.list
  pageInfo.value.total = res.data.total
}

//分割图片名称
const getFineName = (str) => {
  return str.split('.')[0]
}
const insertImgList = async () => {
  await getUserData('insertImage', list.value).then(async (res) => {
    if (res.success) {
      ElMessage({
        message: '头像添加成功',
        type: 'success'
      })
    }
    setTimeout(async () => {
      loading.value = false
      await setUserList()
    }, 1000)
  })
  list.value = []
}
//防抖闭包
const timeClosure = (fn, delay) => {
  let time = null
  return function () {
    if (time) {
      clearTimeout(time)
    }
    time = setTimeout(function () {
      fn()
    }, delay)
  }
}
//全局防抖函数
const de = timeClosure(insertImgList, 1000)
const value1 = ref(1)
const beforeUpload2 = (file) => {
  loading.value = true
  if (file) {
    const reader = new FileReader()
    reader.onload = function (e) {
      const img = new Image()
      img.src = e.target.result
      img.onload = function () {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        // 设置压缩后的图片尺寸
        const maxWidth = 800 // 设置最大宽度
        const maxHeight = 600 // 设置最大高度
        let width = img.width
        let height = img.height
        if (width > maxWidth) {
          height *= maxWidth / width
          width = maxWidth
        }
        if (height > maxHeight) {
          width *= maxHeight / height
          height = maxHeight
        }
        canvas.width = width
        canvas.height = height
        // 绘制图片到 canvas 上
        ctx.drawImage(img, 0, 0, width, height)
        // 目标文件大小（以字节为单位）
        const targetSize = 100 * 1024 // 例如，100 KB
        // 初始图片质量
        let quality = 0.8
        let base64String = canvas.toDataURL('image/jpeg', quality)
        let base64Data = base64String.split(',')[1]
        let fileSize = base64Data.length * 0.75 // Base64 编码会增加大约 33% 的大小
        // 调整图片质量直到文件大小符合要求
        while (fileSize > targetSize && quality > 0.1) {
          quality -= 0.1
          base64String = canvas.toDataURL('image/jpeg', quality)
          base64Data = base64String.split(',')[1]
          fileSize = base64Data.length * 0.75
        }
        let key = String(getFineName(file.name))
        list.value.push({ num: key, pic: base64String })
        console.log(value1.value++)
        de()
      }
    }
    reader.readAsDataURL(file)
  }
}

const handleSelectionChange = (list) => {
  selectList.value = list
}

const deleteRow = async (number) => {
  let res = null
  if (number != null) {
    // dataStore.removeData(number)
    res = await getUserData('delete', [number])
  } else {
    console.log(selectList.value.map((e) => e.num))
    res = await getUserData(
      'delete',
      selectList.value.map((e) => e.num)
    )
  }
  console.log(res)
  setUserList()
  initData(sqliteData)
}

//搜索名字
const search = () => {
  pageInfo.value.page = 1
  setUserList()
}
//重置名字
const reSet = () => {
  searchValue.value = ''
  pageInfo.value.page = 1
  setUserList()
}
//页面大小变化
const handleSizeChange = (size) => {
  pageInfo.value.size = size
  setUserList()
}
//页面数变化
const handleCurrentChange = (page) => {
  pageInfo.value.page = page
  setUserList()
}
//更新table
// const changeTable = () => {
//   pageInfo.value.total = dataStore.getData.length
//   let { page, size } = pageInfo
//   tempList.value = [...dataStore.searchData('姓名', searchValue.value, page, size)]
// }

const beforeUpload = async (file) => {
  getExcelData(file)
}
const getExcelData = async (file) => {
  let fileReader = new FileReader()
  fileReader.readAsArrayBuffer(file)
  fileReader.onload = (e) => {
    try {
      let data = e.target.result
      let workbook = XLSX.read(data, { type: 'binary' })
      const worksheet = workbook.Sheets[workbook.SheetNames[0]]
      const sheetlist = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
      console.log('json', sheetlist)
      // 格式化数据或进行其他操作
      formatDate(sheetlist)
    } catch (e) {
      console.log('文件类型不正确')
    }
  }
}
const mapping = {
  学号: 'num',
  性别: 'sex',
  姓名: 'name',
  头像: 'pic',
  班级: 'class',
  权重: 'weight',
  积分: 'integral'
}
class userObj {
  constructor(name, num, pic, sex, integral, weight) {
    this.name = name
    this.num = num
    this.pic = pic
    this.sex = sex
    this.integral = integral
    this.weight = weight
  }
}
const formatDate = async (sheetlist) => {
  let arrayData = []
  try {
    if (sheetlist.length < 1) return
    // tableColumnLabel.value = sheetlist[0]
    // let temp = 0
    for (let i = 1; i < sheetlist.length; i++) {
      let obj = new userObj()
      for (let j = 0; j < sheetlist[0].length; j++) {
        const columnName = sheetlist[0][j]
        obj[mapping[columnName]] = String(sheetlist[i][j])
      }
      console.log(obj)
      arrayData.push(obj)
      console.log('\n')
    }
    let res = await getUserData('insert', arrayData)
    if (res.success) {
      if (res.success) {
        ElMessage({
          message: '导入数据成功',
          type: 'success'
        })
        await setUserList()
        await initData(sqliteData)
      } else {
        ElMessage({
          message: '导入数据失败',
          type: 'error'
        })
      }
    }
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss" scoped>
.inline-input {
  max-width: 15rem;
}

#search {
  width: 16rem;
}

.search {
  transform: translateX(-10px);
}

#excle,
.avt {
  margin-right: 1rem;
}

.container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  padding: 1em;
}

.search {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.layout_2 {
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 1rem;
  padding-top: 20px;
  position: relative;
}

.footer {
  width: 100%;
  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;
}
</style>
